<?php

namespace app\supplier\controller\product;

use app\common\model\settings\Setting;
use app\common\service\qrcode\PosterService;
use app\Request;
use app\supplier\model\product\Product as ProductModel;
use app\common\model\product\Category as CategoryModel;
use app\supplier\model\product\ProductBrandRelationModel;
use app\supplier\service\ProductService;
use app\supplier\model\supplier\Supplier as SupplierModel;
use app\supplier\controller\Controller;
use app\supplier\model\product\ProductMark;
use app\supplier\model\product\ProductLabel;

/**
 * 商品管理控制器
 */
class Product extends Controller
{
    /**
     * 商品列表(全部)
     */
    public function index()
    {
        $supplier = SupplierModel::detail($this->getSupplierId());
        // 获取全部商品列表
        $model = new ProductModel;
        $list = $model->getListNoCity(array_merge(['status' => -1, 'shop_supplier_id' => $this->getSupplierId()], $this->postData()));
        // 商品分类
        $category = CategoryModel::getCacheTree();
        // 数量
        $product_count = [
            'sell' => $model->getCount('sell', $this->getSupplierId(),$this->postData()),
            'stock' => $model->getCount('stock', $this->getSupplierId(),$this->postData()),
            'recovery' => $model->getCount('recovery', $this->getSupplierId(),$this->postData()),
            'draft' => $model->getCount('draft', $this->getSupplierId(),$this->postData()),
            'lower' => $model->getCount('lower', $this->getSupplierId(),$this->postData()),
            'audit' => $model->getCount('audit', $this->getSupplierId(),$this->postData()),
            'no_audit' => $model->getCount('no_audit', $this->getSupplierId(),$this->postData())
        ];
        return $this->renderSuccess('', compact('list', 'category', 'supplier', 'product_count'));
    }


    /**
     *导出商品
     * export
     * void
     * @return void
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     * @Author kevin
     * @date 2024/5/13 16:22
     */
    public function export(){
        $model = new ProductModel;
        $list = $model->getExportList(array_merge(['status' => -1, 'shop_supplier_id' => $this->getSupplierId()], $this->postData()));
        $category_list = (new CategoryModel()) -> column('name','category_id');
        foreach ($list as $key => $value){
            $category_child_name = $category_list[$value['category']['category_id']]??'';
            $category_parent_name = $category_list[$value['category']['parent_id']]??'';
            $list[$key]['category_name_text'] = $category_parent_name ?$category_parent_name.'-'.$category_child_name:$category_child_name;
        }
        $xls_cell = [
            ['product_id' , '商品ID'],
            ['product_name' , '商品名称'],
            ['category_name_text' , '分类'],
            ['brand_name' , '品牌'],
            ['yieldly' , '产地'],
            ['alcoholic_strength' , '酒精度'],
            ['net_content' , '净含量'],
            ['product_stock' , '库存'],
            ['sales_actual' , '实际销量'],
            ['product_price' , '销售价'],
            ['rate' , '佣金比例（百分比）'],
           ];
        $exp_title = '商品数据' . date('Y-m-d H:i:s');
        exportExcel($exp_title, $xls_cell, $list);
    }

    /**
     * 添加商品
     */
    public function add($scene = 'add')
    {
        // get请求
        if ($this->request->isGet()) {
            //标签
            $labels = (new ProductLabel)->getSelectList(['status'=>1,'audit_status'=>1], $this->getSupplierId(), 'product_label_id as id, label_name as name');
            //标记
            $marks = (new ProductMark)->getSelectList(['status'=>1,'audit_status'=>1], $this->getSupplierId(), 'id, name');
            return $this->getBaseData();
        }
        //post请求
        $data = json_decode($this->postData()['params'], true);
        if ($scene == 'copy') {
            unset($data['create_time']);
            unset($data['sku']['product_sku_id']);
            unset($data['sku']['product_id']);
            unset($data['product_sku']['product_sku_id']);
            unset($data['product_sku']['product_id']);
            // 如果是多规格
            if ($data['spec_type'] == 20) {
                foreach ($data['spec_many']['spec_list'] as &$sku) {
                    $sku['product_sku_id'] = 0;
                }
            }
            //初始化销量等数据
            $data['sales_initial'] = 0;
        }
        //是否需要审核
        $add_audit = Setting::getItem('store')['add_audit'];
        if ($add_audit == 0) {
            // 如果不需要审核，则审核状态是已审核
            $data['audit_status'] = 10;
        }
        $model = new ProductModel;
        if (isset($data['product_id'])) {
            $data['product_id'] = 0;
        }
        $data['shop_supplier_id'] = $this->getSupplierId();

        $data['commission_config_id'] = $model -> where('category_id',$data['category_id']) -> value('commission_config_id');

        $data['search'] = preg_replace('/\s/', '',$data['product_name']);
        if ($model->add($data)) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 获取基础数据
     */
    public function getBaseData()
    {
        return $this->renderSuccess('', array_merge(ProductService::getEditData(null, 'add', $this->getSupplierId()), []));
    }

    /**
     * 获取编辑数据
     */
    public function getEditData($product_id, $scene = 'edit')
    {
        $model = ProductModel::detail($product_id);
        return $this->renderSuccess('', array_merge(ProductService::getEditData($model, $scene, $this->getSupplierId()), compact('model')));
    }

    /**
     * 商品编辑
     */
    public function edit($product_id, $scene = 'edit')
    {
        $model = ProductModel::productDetailNoSup($product_id);
        if ($this->request->isGet()) {
            //标签
            $labels = (new ProductLabel)->getSelectList(['status'=>1,'audit_status'=>1], $this->getSupplierId(), 'product_label_id as id, label_name as name');
            //标记
            $marks = (new ProductMark)->getSelectList(['status'=>1,'audit_status'=>1], $this->getSupplierId(), 'id, name');
            return $this->renderSuccess('', array_merge(ProductService::getEditData($model, $scene, $this->getSupplierId()), compact('model', 'labels', 'marks')));
        }
        if ($scene == 'copy') {
            return $this->add($scene);
        }

        $params = json_decode($this->postData()['params'], true);
        $params['search'] = preg_replace('/\s/', '',$params['product_name']);
        // 更新记录
        if ($model->edit($params, $this->getSupplierId())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 修改商品状态
     */
    public function state($product_id, $state)
    {
        // 商品详情
        $model = ProductModel::productDetail($product_id, $this->getSupplierId());
        if ($model['audit_status'] != 10) {
            return $this->renderError('商品状态不正确');
        }
        if (!$model->setStatus($state)) {
            return $this->renderError('操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 删除商品
     */
    public function delete($product_id)
    {
        // 商品详情
        $model = ProductModel::productDetail($product_id, $this->getSupplierId());
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    public function createQrcode(Request $request)
    {
        $params = $request->param();
        $product = \app\common\model\product\Product::where('product_id', '=', $params['product_id'])->find();
        $Qrcode = new \app\common\service\qrcode\ProductService($product, 0, 'wx');
        return $this->renderSuccess('添加成功', $Qrcode->createProductQrCode($params['product_id'],$product['is_show']));
    }
}
